package com.yunduo.controller.front;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yunduo.common.RetunData.CommonReturn;
import com.yunduo.common.RetunData.statuscode.impl.ResultCode;
import com.yunduo.entity.Good;
import com.yunduo.entity.Shop;
import com.yunduo.entity.ShopGoods;
import com.yunduo.entity.vo.ShopData;
import com.yunduo.service.GoodService;
import com.yunduo.service.ShopGoodsService;
import com.yunduo.service.ShopService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * 小程序端首页显示控制器
 */
@RestController
@RequestMapping("/findex")
public class IndexDataController {

    @Resource
    private ShopGoodsService shopGoodsService;
    @Resource
    private ShopService shopService;
    @Resource
    private GoodService goodService;

    //根据店铺商品id查找最新上架的三个商品
    @PostMapping("/getShopData")
    public CommonReturn getShopDatas(@RequestBody String[] ids){
        List<ShopData> list = new ArrayList<>();
        for (String id : ids) {
            Shop shop = shopService.getById(id);
            List<ShopGoods> shopData = shopGoodsService.list(new LambdaQueryWrapper<ShopGoods>().eq(ShopGoods::getShopId, id));
            List<String> goodIds = shopData.stream().map(ShopGoods::getGoodId).collect(Collectors.toList());
            List<Good> goodData = goodService.seletGoodByIdsOrderPop(goodIds,3);
            list.add(new ShopData(shop,goodData));
        }
        return CommonReturn.SUCCESS(ResultCode.SUCCESS).setData("list",list);
    }

    //查询热度排名前3的店铺进行展示 返回店铺id
    @GetMapping("/getPopShop")
    public CommonReturn getPopShop(){
        List<Shop> list = shopService.getShopOrderByPop(3);
        List<String> shopIds = list.stream().map(Shop::getId).collect(Collectors.toList());
        return CommonReturn.SUCCESS(ResultCode.SUCCESS).setData("list",shopIds);
    }

    //查询最新上架的8个商品
    @GetMapping("/getNewGood")
    public CommonReturn getNewGood(){
        LambdaQueryWrapper<Good> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Good::getGmtCreate);
        List<Good> list = goodService.seletGoodByOrderPop(8);
        return CommonReturn.SUCCESS(ResultCode.SUCCESS).setData("list",list);
    }

    //最多随机返回8个商品
    @GetMapping("/getGoodDatas")
    public CommonReturn getGoodDatas(){
        int count = goodService.count(new LambdaQueryWrapper<Good>());
        Random random = new Random();
        int result = random.nextInt(count+1);
        List<Good> list = goodService.selectGoodsForN(result, 8);
        return CommonReturn.SUCCESS(ResultCode.SUCCESS).setData("list",list);
    }
}
